package com.yanq.liancar.activity;
/*
 *  @创建者     liyan
 *  @创建时间   2018/11/10  11:08
 *  @描述       ${TODO}
 */


import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.vondear.camera.tool.RxCameraTool;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.RxBarTool;
import com.vondear.rxtool.RxPhotoTool;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.view.dialog.RxDialog;
import com.vondear.rxui.view.dialog.RxDialogSure;
import com.yanq.liancar.R;
import com.yanq.liancar.activity.base.BaseToolbarActivity;
import com.yanq.liancar.bean.BqueryShopAllTypeBean;
import com.yanq.liancar.bean.QueryByoNumBean;
import com.yanq.liancar.bean.ServiceScanerBean;
import com.yanq.liancar.bean.UserBean;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.LogUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zbar.ZBarView;

public class ScanerCodeActivity extends BaseToolbarActivity {

    @BindView(R.id.action_bar)
    AppBarLayout actionBar;
    @BindView(R.id.zxingview)
    ZBarView mQRCodeView;
    @BindView(R.id.top_mask)
    ImageView topMask;
    @BindView(R.id.top_openpicture)
    ImageView topOpenpicture;
    @BindView(R.id.rl_title)
    LinearLayout rlTitle;
    @BindView(R.id.tv_content)
    TextView tv_content;
    private boolean isOpen;
    private String where;
    private RxDialogSure mRxDialog;
    private int sid;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scanercode);
        ButterKnife.bind(this);
        mTvTitle.setText("扫描二维码");
        where = getIntent().getStringExtra("where");

        if ("BindOBDActivity".equals(where) || "BindCarActivity".equals(where)) {
            tv_content.setVisibility(View.GONE);
        } else {
            sid = getIntent().getIntExtra("sid", 0);
            LogUtils.e("sid=====", sid+"");
        }
        ImmersionBar.with(this).statusBarDarkFont(true).statusBarColor(R.color.white).init();
        mQRCodeView.setDelegate(new QRCodeView.Delegate() {
            /**
             * 处理扫描结果
             *
             * @param result 摄像头扫码时只要回调了该方法 result 就一定有值，不会为 null。解析本地图片或 Bitmap 时 result 可能为 null
             */

            @Override
            public void onScanQRCodeSuccess(String result) {
                LogUtils.e("mQRCodeView", "result:" + result);

                vibrate();

                if ("BindOBDActivity".equals(where)) {
                    Intent intent = new Intent();
                    intent.putExtra("code", result);
                    setResult(RESULT_OK, intent);
                    finish();
                } else if ("BHomeFragment".equals(where)) {
                    if (result.indexOf("OrderDetails") == 0) {
                        LogUtils.e("asdasdasfasdadasfas",result.indexOf("OrderDetails")+"========="+result.substring(12));
                        orderScaner(result.substring(12));
                    } else {
                        serviceScaner(result);
                    }

                } else if ("BindCarActivity".equals(where)) {
                    Intent intent = new Intent();
                    intent.putExtra("code", result);
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }

            /**
             * 摄像头环境亮度发生变化
             *
             * @param isDark 是否变暗
             */
            @Override
            public void onCameraAmbientBrightnessChanged(boolean isDark) {
                //                // 这里是通过修改提示文案来展示环境是否过暗的状态，接入方也可以根据 isDark 的值来实现其他交互效果
                //
                //                String tipText = mQRCodeView.getScanBoxView().getTipText();
                //                LogUtils.e("tipText", tipText);
                //                LogUtils.e("tipText", tipText);
                //                LogUtils.e("tipText", tipText);
                //                LogUtils.e("tipText", tipText);
                //                LogUtils.e("tipText", tipText);
                //                String ambientBrightnessTip = "\n环境过暗，请打开闪光灯";
                //
                //                if (isDark) {
                //
                //                    if (!tipText.contains(ambientBrightnessTip)) {
                //
                //                        mQRCodeView.getScanBoxView().setTipText(tipText + ambientBrightnessTip);
                //
                //                    }
                //
                //                } else {
                //
                //                    if (tipText.contains(ambientBrightnessTip)) {
                //
                //                        tipText = tipText.substring(0, tipText.indexOf(ambientBrightnessTip));
                //
                //                        mQRCodeView.getScanBoxView().setTipText(tipText);
                //
                //                    }
                //
                //                }
            }

            /**
             * 处理打开相机出错
             */
            @Override
            public void onScanQRCodeOpenCameraError() {

            }
        });
    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    @OnClick({R.id.top_mask, R.id.top_openpicture})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.top_mask:
                if (!isOpen) {
                    RxCameraTool.openFlashLight();
                    isOpen = true;
                } else {
                    RxCameraTool.closeFlashLight();
                    isOpen = false;
                }
                break;
            case R.id.top_openpicture:
                RxPhotoTool.openLocalImage(this);
                break;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        mQRCodeView.startCamera(); // 打开后置摄像头开始预览，但是并未开始识别
        //mZBarView.startCamera(Camera.CameraInfo.CAMERA_FACING_FRONT); // 打开前置摄像头开始预览，但是并未开始识别
        mQRCodeView.startSpotAndShowRect(); // 显示扫描框，并且延迟0.1秒后开始识别
    }

    @Override
    protected void onStop() {
        mQRCodeView.stopCamera();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        mQRCodeView.onDestroy();
        super.onDestroy();
    }

    //扫描订单二维码
    private void orderScaner(String str) {
        OkGo.<String>post(Config.s + "llc/carServiceOrderController/queryByoNum")
                .tag(this)
                .params("oNum", str)
                .params("shopid", sid)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        QueryByoNumBean byoNumBean = gson.fromJson(response.body(), QueryByoNumBean.class);
                        if (byoNumBean.isIsSuccess()) {
                            if (byoNumBean.getCode() == 200) {
                                if (byoNumBean.getData().getOrder().getServiceType()==5){
                                    Bundle bundle=new Bundle();
                                    bundle.putString("oNum",byoNumBean.getData().getOrder().getOnum());
                                    RxActivityTool.skipActivity(ScanerCodeActivity.this, SheetMetalActivity.class,bundle);
                                }else {
                                    Intent intent = new Intent(ScanerCodeActivity.this, VerificationResultActivity.class);
                                    intent.putExtra("code", byoNumBean.getData().getOrder().getOnum());
                                    intent.putExtra("shopName", byoNumBean.getData().getShop().getShopName());
                                    intent.putExtra("serviceName", byoNumBean.getData().getOrder().getServiceName());
                                    intent.putExtra("type",1);
                                    startActivity(intent);
                                }
                            } else {
                                dialog(byoNumBean.getOutputMessage());
                            }
                        } else {
                            RxToast.error(byoNumBean.getOutputMessage());
                            // 显示扫描框，并且延迟0.1秒后开始识别
                            mQRCodeView.startSpotAndShowRect();
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        RxToast.error("服务器连接错误");
                    }
                });
    }


    //扫描服务券二维码
    private void serviceScaner(String str) {
        OkGo.<String>post(Config.s + "llc/api/serviceVoucherController/consumeVoucher")
                .tag(this)
                .params("token", UserBean.getbToken(this))
                .params("typeCode", str)
                .params("shopid", sid)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        ServiceScanerBean bean = gson.fromJson(response.body(), ServiceScanerBean.class);
                        if (bean.isIsSuccess()) {
                            if (bean.getCode() == 200) {
                                if (bean.getData().getServiceType()==5){
                                    Bundle bundle=new Bundle();
                                    bundle.putString("oNum",bean.getData().getONum());
                                    RxActivityTool.skipActivity(ScanerCodeActivity.this, SheetMetalActivity.class,bundle);
                                }else {
                                    Intent intent = new Intent(ScanerCodeActivity.this, VerificationResultActivity.class);
                                    intent.putExtra("code", bean.getData().getONum());
                                    intent.putExtra("shopName", bean.getData().getShopName());
                                    intent.putExtra("serviceName", bean.getData().getServiceName());
                                    intent.putExtra("type",2);
                                    startActivity(intent);
                                }
                            } else {
                                dialog(bean.getOutputMessage());
                            }
                        } else {
                            RxToast.error(bean.getOutputMessage());
                            // 显示扫描框，并且延迟0.1秒后开始识别
                            mQRCodeView.startSpotAndShowRect();
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        RxToast.error("服务器连接错误");
                    }
                });
    }


    private void dialog(String str) {
        mRxDialog = new RxDialogSure(this);
        mRxDialog.setTitle("验证码错误");
        mRxDialog.setContent(str);

        mRxDialog.setSureListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mRxDialog.dismiss();
                // 显示扫描框，并且延迟0.1秒后开始识别
                mQRCodeView.startSpotAndShowRect();
            }
        });
    }
}
